import json

from flask import Blueprint, jsonify, request

from utils.db import db1
from utils.redisconn import r
from utils.comm import get_data

bp_workflow = Blueprint('workflow',__name__)


@bp_workflow.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


@bp_workflow.route("/getsource")
def getsource():
    values = r.get_str("datasource")
    if values:
        lst = eval(values)
    else:
        sql = "select * from data_source"
        res = db1.find_all(sql)
        lst = []
        if res:
            for i in res:
                dic = {"id":i["id"],"name":i["name"]}
                msql = "select id,name,type from %s"%i["tablename"]
                mres = db1.find_all(msql)
                dic["mes"] = mres
                lst.append(dic)
        r.set_str("datasource",json.dumps(lst))

    return jsonify({"code":200,"list":lst})

@bp_workflow.route('/addworkflow',methods=["POST"])
def addworkflow():
    data = get_data()
    sql = "select * from workflow where id=%d"%int(data["id"])
    res = db1.find(sql)
    if res:
        # print(json.loads(data["list"]))
        # data["list"] = json.loads(data["list"])
        # for i in data["list"]:
        #     i["value"]=json.loads(i["value"])
        # print(data["list"])
        usql = "update workflow set params='%s' where id=%d"%(str(data["list"]),int(res["id"]))
        db1.update(usql)
    return jsonify({"code":200,"msg":"修改成功"})

# 查询工作流
@bp_workflow.route("/query_workflow")
def query_workflow():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})



# 添加
@bp_workflow.route('/addworkflow')
def addworkflow():
    data = get_data()
    print(data)

    return jsonify({'code':200,'mes':'ok'})